package com.wangnan.currentactivity.service;

import android.accessibilityservice.AccessibilityService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.IntentFilter;
import android.os.Build;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;

import com.wangnan.currentactivity.BaseApplication;
import com.wangnan.currentactivity.extract.IData;
import com.wangnan.currentactivity.extract.RecycleDetailsExtract;
import com.wangnan.currentactivity.extract.factory.AlipayBillingFactory;
import com.wangnan.currentactivity.extract.factory.DataFactory;
import com.wangnan.currentactivity.extract.factory.MTBillFactory;
import com.wangnan.currentactivity.extract.factory.WeChatBillingFactory;
import com.wangnan.currentactivity.extract.factory.WeChatRedPacketFactory;
import com.wangnan.currentactivity.extract.factory.YSFBillFactory;
import com.wangnan.currentactivity.receiver.MAccessibilityServiceReceiver;
import com.wangnan.currentactivity.ui.activity.MainActivity;
import com.wangnan.currentactivity.ui.window.WindowViewContainer;
import com.wangnan.currentactivity.util.ActivityUtil;
import com.wangnan.currentactivity.util.NotificationUtil;

/**
 *
 */

public class MAccessibilityService extends AccessibilityService {
	/**
	 * 辅助服务名称（包名+"/"+完整类名）
	 */
	public static final String SERVCE_NAME     = "com.wangnan.currentactivity/com.wangnan.currentactivity.service.MAccessibilityService";
	/**
	 * 通知栏ID
	 */
	public static final int    NOTIFICATION_ID = 0x1000;
	public static       String theCurrentPage  = "AA";

	/**
	 * 窗口视图容器
	 */
	private WindowViewContainer mWindowViewContainer;
	private MainActivity        mainActivity = new MainActivity();

	/**
	 * 广播接收器
	 */
	private MAccessibilityServiceReceiver mReceiver;

	/**
	 * 通知栏管理器
	 */
	private NotificationManager mNotificationManager;

	/**
	 * 服务连接完成
	 */
	@Override
	protected void onServiceConnected() {
		//		// 添加窗口
		//		mWindowViewContainer = WindowViewContainer.getInstance(this);
		//		mWindowViewContainer.addWindowView();
		// 添加通知栏消息（将服务提升到前台）
		addNotification();
		// 注册广播接收器
		mReceiver = new MAccessibilityServiceReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(MAccessibilityServiceReceiver.SWITCH_ACTION);
		intentFilter.addAction(MAccessibilityServiceReceiver.CLOSE_ACTION);
		registerReceiver(mReceiver, intentFilter);
	}

	/**
	 * 添加通知
	 */
	private void addNotification() {
		// 获取通知管理器
		mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		// Android O以上需要配置通知渠道
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			NotificationChannel channel = new NotificationChannel(NotificationUtil.CHANNEL_ID, NotificationUtil.CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
			mNotificationManager.createNotificationChannel(channel);
		}
		// 获取Notification实例
		Notification notification = NotificationUtil.getNotificationByVersion(this);
		// 将辅助服务设置为前台服务
		startForeground(NOTIFICATION_ID, notification);
		// 显示Notification
		if (mNotificationManager != null) {
			mNotificationManager.notify(NOTIFICATION_ID, notification);
		}
	}

	/**
	 * 接收辅助服务事件
	 */
	@Override
	public void onAccessibilityEvent(AccessibilityEvent event) {
		RecycleDetailsExtract a = new RecycleDetailsExtract();
		if (event == null) {
			return;
		}
		switch (event.getEventType()) {
			case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED: // 窗口状态改变
				if (event.getPackageName() != null && event.getClassName() != null) {
					ActivityUtil.globalDeleteClearlist();
					Log.e("zzh", "onAccessibilityEvent进入清空实体类数据: ");
					Log.e("zzh", "当前页面: " + event.getClassName().toString());
					//判断进入界面
					if (event.getClassName().toString().equals("com.alipay.mobile.nebulax.integration.mpaas.activity.NebulaActivity$Main")) {
						newIsType(new AlipayBillingFactory(), a, "支付宝账单界面");
					} else if (event.getClassName().toString().equals("com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyDetailUI")) {
						newIsType(new WeChatRedPacketFactory(), a, "微信红包详情界面");            //判断进入微信红包详情界面
					} else if (event.getClassName().toString().equals("com.unionpay.cordova.UPActivityWeb")) {
						newIsType(new YSFBillFactory(), a, "云闪付账单详情界面");     //判断进入云闪付账单详情列表界面
					} else if (event.getClassName().toString().equals("com.tencent.mm.plugin.webview.ui.tools.WebViewUI")) {
						theCurrentPage = event.getClassName().toString();
					} else if (event.getClassName().toString().equals("com.meituan.android.base.knb.KNBWebViewActivity")) {
						theCurrentPage = event.getClassName().toString();
					}
				}
				break;
			case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED: // 窗口状态改变
				if (theCurrentPage.equals("com.tencent.mm.plugin.webview.ui.tools.WebViewUI")) {
					Log.e("zzh", "进入了微信账单列表界面" + event.getClassName().toString());
					ActivityUtil.globalDeleteClearlist();
					Log.e("zzh", "进入了微信账单列表进入清空实体类数据: ");
					ActivityUtil.isDetail(this.getRootInActiveWindow());
					if (BaseApplication.isDetail == 1) {
						if (BaseApplication.isFistWx == 0) {
							BaseApplication.isFistWx++;
							newIsType(new WeChatBillingFactory(), a,  "微信账单详情界面");               //判断进入微信账单列表界面
						} else {
							return;
						}
					}
				}
				if (theCurrentPage.equals("com.meituan.android.base.knb.KNBWebViewActivity")) {
					Log.e("zzh", "进入了美团账单列表界面" + event.getClassName().toString());
					Log.e("zzh", "进入了美团账单列表进入清空实体类数据: ");
					ActivityUtil.globalDeleteClearlist();
					ActivityUtil.isDetail(this.getRootInActiveWindow());
					if (BaseApplication.isDetail == 2) {
						if (BaseApplication.isFistMt == 0) {
							BaseApplication.isFistMt++;
							newIsType(new MTBillFactory(), a, "美团账单详情界面");     //判断进入美团账单详情列表界面
						} else {
							return;
						}
					}
				}
				break;
			default:
				break;
		}
	}

	/**
	 * 服务中断
	 */
	@Override
	public void onInterrupt() {
	}

	/**
	 * 服务退出
	 */
	@Override
	public void onDestroy() {
		// 移除窗口视图，销毁视图容器
		if (mWindowViewContainer != null) {
			mWindowViewContainer.destory();
			mWindowViewContainer = null;
		}
		// 取消通知栏消息显示
		if (mNotificationManager != null) {
			mNotificationManager.cancel(MAccessibilityService.NOTIFICATION_ID);
			mNotificationManager = null;
		}
		// 解注册广播接收器
		if (mReceiver != null) {
			unregisterReceiver(mReceiver);
			mReceiver = null;
		}
		// 如果主界面未被销毁，更新主界面UI
		if (MainActivity.mActivity != null) {
			MainActivity.mActivity.updateUI();
		}
		// 停止前台服务
		stopForeground(true);
		super.onDestroy();
	}

	/**
	 * 判断进入支付宝，微信，云闪付，美团
	 */
	public void newIsType(DataFactory factory, RecycleDetailsExtract recycleDetailsExtract, String type) {
		try {
			for (int i = 0; i < 100; i++) {
				Log.e("zzh", "进入计数类型:" + type + "-----------------------" + i + "------");
				if (i == 50) {
					Log.e("zzh", "进入2秒休眠:" + type + "-----------------------" + i + "------");
					Thread.sleep(2050);
				}
				if (i == 99) {
					recycleDetailsExtract.recycleDetails(this.getRootInActiveWindow(), type);
					//用工厂模式 得出数据
					IData dataFactory = factory.createData();
					dataFactory.Data();
				}
			}
		} catch (Exception e) {
			System.out.println("Wrong!");
			Log.e("zzh", "在执行延迟循环报异常: " + e);
		}
	}
}
